package com.gandong8.trace.tool.config.aliyun.ons;

import com.gandong8.trace.tool.config.GlobalProperties;
import com.gandong8.trace.tool.config.aliyun.ons.properties.OnsProducerProperties;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Properties;

@Configuration
@EnableConfigurationProperties({OnsProducerProperties.class, GlobalProperties.class})
@Slf4j
public class OnsProducerConf {

    @Autowired
    private OnsProducerProperties producerProperties;

    @Autowired
    private GlobalProperties globalProperties;


    @Bean(name="onsProducer", destroyMethod = "shutdown")
    public ProducerBean createProducer() {
        if(!globalProperties.getOnsProducerOpen()) {
            System.err.println("ons producer not allowed");
            return null;
        }
        Properties properties = initProperties();
        ProducerBean producerBean = new ProducerBean();
        producerBean.setProperties(properties);
        producerBean.start();
        log.info("----ons producer server start!-----");
        return producerBean;
    }

    private Properties initProperties() {
        Properties prop = new Properties();
        prop.put(PropertyKeyConst.AccessKey, producerProperties.getAccessKey());
        prop.put(PropertyKeyConst.SecretKey, producerProperties.getAccessSecret());
        prop.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, producerProperties.getTimeOut());
        prop.put(PropertyKeyConst.NAMESRV_ADDR, producerProperties.getNamesrvAddr());
        return prop;
    }

    @PostConstruct
    public void initLog() {
        //System.setProperty(ClientLogger.CLIENT_LOG_USESLF4J, "true");
        //System.setProperty(ClientLogger.CLIENT_LOG_LEVEL, "ERROR");
    }
}
